<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="所属场所" prop="placeId">
        <el-select v-model="queryParams.placeId" filterable placeholder="请选择场所" @change="handleQuery">
          <el-option
            v-for="item in placeList"
            :key="item.placeId"
            :label="item.placeName+'/ '+ item.status"
            :value="item.placeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="注册代码" prop="registrationCode">
        <el-input
          v-model="queryParams.registrationCode"
          placeholder="请输入注册代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电梯出厂编号" prop="factoryNumber">
        <el-input
          v-model="queryParams.factoryNumber"
          placeholder="请输入电梯出厂编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.bus_elevator_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:elevator:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:elevator:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:elevator:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:elevator:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="elevatorList" @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="所属场所" align="center" prop="placeId" width="120">
        <template slot-scope="scope">
          <span v-for="item in placeList" v-if="scope.row.placeId === item.placeId">{{ item.placeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册代码/电梯出厂编号" align="center" prop="registrationCode" >
        <template slot-scope="scope">
          <span>{{ scope.row.registrationCode }}/{{ scope.row.factoryNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="台数" align="center" prop="num" />
      <el-table-column label="电梯品牌/电梯型号" align="center" prop="brand" >
        <template slot-scope="scope">
          <span>{{ scope.row.brand }}/{{ scope.row.model }}</span>
        </template>
      </el-table-column>
      <el-table-column label="层/站/门" align="center" prop="floors" >
        <template slot-scope="scope">
          <span>{{ scope.row.floors }}/{{ scope.row.stops }}/{{ scope.row.doors }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运行地点" align="center" prop="detailedLocation" />
      <el-table-column label="保养金额(元/台/月)" align="center" prop="maintainAmount" />
      <el-table-column label="安装日期" align="center" prop="installedDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次维护日期" align="center" prop="lastMaintenanceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastMaintenanceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电梯状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_elevator_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleInfo(scope.row)"
            v-hasPermi="['business:elevator:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:elevator:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:elevator:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电梯信息，用于存储电梯的基本信息及其所属场所对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属场所" prop="placeId">
              <el-select v-model="form.placeId" filterable placeholder="请选择场所" style="width: 300px">
                <el-option
                  v-for="item in placeList"
                  :key="item.placeId"
                  :label="item.placeName+' / '+ item.status"
                  :value="item.placeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" placeholder="请输入排序字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册代码" prop="registrationCode">
              <el-input v-model="form.registrationCode" placeholder="请输入注册代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="台数" prop="registrationCode">
              <el-input-number v-model="form.num" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电梯出厂编号" prop="factoryNumber">
              <el-input v-model="form.factoryNumber" placeholder="请输入电梯出厂编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电梯品牌" prop="brand">
              <el-autocomplete
                class="inline-input"
                v-model="form.brand"
                :fetch-suggestions="querySearchBrand"
                placeholder="请输入电梯品牌"
                @select="handleSelectBrand"
                style="width: 280px"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="model">
              <el-autocomplete
                class="inline-input"
                v-model="form.model"
                :fetch-suggestions="querySearchModel"
                placeholder="请输入型号"
                @select="handleSelectModel"
                style="width: 280px"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层数" prop="floors">
              <el-input-number v-model="form.floors" placeholder="请输入层数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站数" prop="stops">
              <el-input-number v-model="form.stops" placeholder="请输入站数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门数" prop="doors">
              <el-input-number v-model="form.doors" placeholder="请输入门数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行地点" prop="detailedLocation">
              <el-input v-model="form.detailedLocation" placeholder="请输入详细地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保养金额(元/台/月)" prop="doors">
              <el-input-number v-model="form.maintainAmount" placeholder="请输入门数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装日期" prop="installedDate">
              <el-date-picker clearable
                              v-model="form.installedDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择安装日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次维护日期" prop="lastMaintenanceDate">
              <el-date-picker clearable
                              v-model="form.lastMaintenanceDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择上次维护日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看电梯的基本信息及其所属场所对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="60%" append-to-body :close-on-click-modal="false">
      <el-descriptions border>
        <el-descriptions-item label="所属场所">
          <span v-for="item in placeList" v-if="form.placeId === item.placeId">{{ item.placeName }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="注册代码">
          {{form.registrationCode}}
        </el-descriptions-item>
        <el-descriptions-item label="台数">{{ form.num }}</el-descriptions-item>
        <el-descriptions-item label="电梯出厂编号">{{ form.factoryNumber }} </el-descriptions-item>
        <el-descriptions-item label="电梯品牌">{{form.brand}}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{form.model}}</el-descriptions-item>
        <el-descriptions-item label="层数">{{form.floors}}</el-descriptions-item>
        <el-descriptions-item label="站数">{{form.stops}}</el-descriptions-item>
        <el-descriptions-item label="门数">{{form.doors}}</el-descriptions-item>
        <el-descriptions-item label="运行地点">{{form.detailedLocation}}</el-descriptions-item>
        <el-descriptions-item label="保养金额(元/台/月)">{{form.maintainAmount}}</el-descriptions-item>
        <el-descriptions-item label="安装日期">
          <span>{{ parseTime(form.installedDate, '{y}-{m}-{d}') }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="上次维护日期">
          <span>{{ parseTime(form.lastMaintenanceDate, '{y}-{m}-{d}') }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{form.remark}}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listElevator, getElevator, delElevator, addElevator, updateElevator } from "@/api/business/elevator";
import { listPlace } from "@/api/business/place";

export default {
  name: "Elevator",
  dicts: ['bus_elevator_status'],
  data() {
    return {
      // 电梯品牌选项
      brandsRestaurants: [],
      // 电梯品牌类型选项
      modelRestaurants: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电梯信息
      elevatorList: [],
      // 场所信息表格数据
      placeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        placeId: null,
        serialNumber: null,
        registrationCode: null,
        factoryNumber: null,
        floors: null,
        stops: null,
        doors: null,
        detailedLocation: null,
        latitude: null,
        longitude: null,
        maintainAmount: null,
        brand: null,
        model: null,
        installedDate: null,
        lastMaintenanceDate: null,
        status: null,
        sortOrder: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        placeId: [
          { required: true, message: "场所ID不能为空", trigger: "blur" }
        ],
        registrationCode: [
          { required: true, message: "注册代码不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "电梯状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getPlaceList();
    this.getList();
  },
  methods: {
    /** 获取场所列表*/
    getPlaceList(){
      listPlace({pageSize: 10000}).then(response => {
        this.placeList = response.rows;
      });

    },
    /** 查询电梯信息 */
    getList() {
      this.loading = true;
      listElevator(this.queryParams).then(response => {
        this.elevatorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        elevatorId: null,
        placeId: null,
        serialNumber: null,
        registrationCode: null,
        factoryNumber: null,
        floors: null,
        stops: null,
        doors: null,
        detailedLocation: null,
        latitude: null,
        longitude: null,
        brand: null,
        model: null,
        installedDate: null,
        lastMaintenanceDate: null,
        status: null,
        sortOrder: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        maintainAmount: null,
        num: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.elevatorId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电梯信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const elevatorId = row.elevatorId || this.ids
      getElevator(elevatorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改电梯信息";
      });
    },
    /** 查看按钮操作 */
    handleInfo(row) {
      this.reset();
      const elevatorId = row.elevatorId || this.ids
      getElevator(elevatorId).then(response => {
        this.form = response.data;
        this.openInfo = true;
        this.title = "查看电梯信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.elevatorId != null) {
            updateElevator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addElevator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const elevatorIds = row.elevatorId || this.ids;
      this.$modal.confirm('是否确认删除电梯信息，用于存储电梯的基本信息及其所属场所编号为"' + elevatorIds + '"的数据项？').then(function() {
        return delElevator(elevatorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/elevator/export', {
        ...this.queryParams
      }, `电梯信息导出_${new Date().getTime()}.xlsx`)
    },
    // 添加电梯信息合计
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = '合计';
          return;
        }
        // 仅对 num 和 maintainAmount 字段进行计算
        if (column.property === 'num' || column.property === 'maintainAmount') {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value)) ) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if (column.property === 'num') {
              sums[3] = `电梯共： ${sum} 台`;
            } else if (column.property === 'maintainAmount') {
              sums[5] = `保养金额： ${sum * 12} 元 / 年`;
              sums[7] = `保养金额： ${sum } 元 / 月`;
            }
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    querySearchBrand(queryString, cb) {
      var brandsRestaurants = this.brandsRestaurants;
      var results = queryString ? brandsRestaurants.filter(this.createFilter(queryString)) : brandsRestaurants;
      console.log("results",results);
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchModel(queryString, cb) {
      var modelRestaurants = this.modelRestaurants;
      var results = queryString ? modelRestaurants.filter(this.createFilter(queryString)) : modelRestaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAllBrand() {
      // 判断本地缓存是否有品牌数据
      if (localStorage.getItem('brands') ) {
        return JSON.parse(localStorage.getItem('brands'));
      } else {
        return [
          { "value": "日立电梯"},
          { "value": "三菱电梯"},
          { "value": "东芝电梯"},
          { "value": "富士达电梯"},
          { "value": "现代电梯"},
          { "value": "奥的斯电梯"},
          { "value": "迅达电梯"},
          { "value": "通力电梯"},
          { "value": "蒂升电梯"},
          { "value": "其他电梯"},
        ]
      }
    },
    loadAllModel() {
      // 判断本地缓存是否有电梯品牌型号数据
      if (localStorage.getItem('brands_models')) {
        return JSON.parse(localStorage.getItem('brands_models'));
      } else {
        return []
      }
    },
    handleSelectBrand(item) {

    },
    handleSelectModel(item) {

    },
  },
  mounted() {
    this.brandsRestaurants = this.loadAllBrand();
    this.modelRestaurants = this.loadAllModel();
  }
};
</script>
